package com.atguigu.cloud.common.mail.service;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.atguigu.cloud.common.mail.entity.SysMailConfig;
import com.atguigu.cloud.common.mail.entity.SysMailTemplateConfig;
import com.atguigu.cloud.common.mail.mapper.SysMailTemplateConfigMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@SuppressWarnings("all")
@Service
public class MailService {
    // 发件人的 邮箱 和 密码（替换为自己的邮箱和密码）
    // PS: 某些邮箱服务器为了增加邮箱本身密码的安全性，给 SMTP 客户端设置了独立密码（有的邮箱称为“授权码”）,
    //     对于开启了独立密码的邮箱, 这里的邮箱密码必需使用这个独立密码（授权码）。
    public static String myEmailAccount = "1114313006@qq.com";
    @Resource
    private Configuration cfg;
    @Resource
    private SysMailTemplateConfigMapper sysMailTemplateConfigMapper;
    @Autowired
    @Qualifier(value = "mailSendSession")
    private Session sessionSend;
    @Autowired
    @Qualifier(value = "sysSendMailConfig")
    private SysMailConfig sysSendMailConfig;

    /**
     * 群发生日邮件
     * @param jsonArray
     * @return
     */
    public MimeMessage sendEmail(String json){
        // 1. 创建一封邮件
        MimeMessage message = new MimeMessage(sessionSend);

        JSONObject jsonObject = JSONObject.parseObject(json);
        JSONArray jsonArray = jsonObject.getJSONArray("emailAddressList");
        System.out.println(jsonArray);
        String templateName = jsonObject.get("templateName").toString();
        String contentBody = jsonObject.get("contentBody").toString();
        InternetAddress[] internetAddresses = new InternetAddress[jsonArray.size()];
        try {
            for(int i = 0;i < jsonArray.size();i++){
                internetAddresses[i] = new InternetAddress(jsonArray.getString(i),"XX用户", "UTF-8");
            }

            QueryWrapper<SysMailTemplateConfig> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("template_type",templateName);
            // 创建发送生日邮件模板对象
            Template template = cfg.getTemplate(sysMailTemplateConfigMapper.selectOne(queryWrapper).getTemplate());
            Map<String, Object> templateData = new HashMap<>();
            templateData.put("content", contentBody);
            StringWriter writer = new StringWriter(); // 使用StringWriter来收集渲染后的HTML内容
            template.process(templateData, writer); // 渲染模板到StringWriter对象
            String emailBody = writer.toString(); // 获取渲染后的HTML内容作为邮件正文
            writer.close(); // 关闭StringWriter

            // 2. From: 发件人
            message.setFrom(new InternetAddress(myEmailAccount, sysSendMailConfig.getPersonnal(), "UTF-8"));
            // 3. To: 收件人（可以增加多个收件人、抄送、密送）
            message.setRecipients(MimeMessage.RecipientType.TO, internetAddresses);
            // 4. Subject: 邮件主题
            message.setSubject("主题", "UTF-8");
            // 5. Content: 邮件正文（可以使用html标签）
            message.setContent(emailBody, "text/html;charset=UTF-8");
            // 6. 设置发件时间
            message.setSentDate(new Date());
            // 7. 保存设置
            message.saveChanges();

            Transport transport = sessionSend.getTransport();
            transport.connect(myEmailAccount, sysSendMailConfig.getPassword());
            // 8. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
            transport.sendMessage(message, message.getAllRecipients());
            // 9. 关闭连接
            transport.close();
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        } catch (UnsupportedEncodingException e) {
            System.out.println("检测到未知的编码");
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (TemplateException e) {
            throw new RuntimeException(e);
        }
        return message;
    }

    /**
     * 批量发送生日邮件
     * @param jsonArray
     * @return
     */
    public MimeMessage sendBirthDayMailBatch(JSONArray jsonArray,String templateName){
        // 1. 创建一封邮件
        MimeMessage message = new MimeMessage(sessionSend);
        try {
            for(int i = 0;i < jsonArray.size();i++){
                Transport transport = sessionSend.getTransport();
                transport.connect(myEmailAccount, sysSendMailConfig.getPassword());
                QueryWrapper<SysMailTemplateConfig> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("template_type",templateName);
                // 创建发送生日邮件模板对象
                Template template = cfg.getTemplate(sysMailTemplateConfigMapper.selectOne(queryWrapper).getTemplate());
                Map<String, Object> templateData = new HashMap<>();
                templateData.put("name", jsonArray.getJSONObject(i).get("employee_name").toString()); // 添加模板数据
                StringWriter writer = new StringWriter(); // 使用StringWriter来收集渲染后的HTML内容
                template.process(templateData, writer); // 渲染模板到StringWriter对象
                String emailBody = writer.toString(); // 获取渲染后的HTML内容作为邮件正文
                writer.close(); // 关闭StringWriter

                // 2. From: 发件人
                message.setFrom(new InternetAddress(myEmailAccount, sysSendMailConfig.getPersonnal(), "UTF-8"));
                // 3. To: 收件人（可以增加多个收件人、抄送、密送）
                message.setRecipient(MimeMessage.RecipientType.TO,new InternetAddress(jsonArray.getJSONObject(i).get("employee_address").toString(),"XX用户", "UTF-8"));
                // 4. Subject: 邮件主题
                message.setSubject("主题", "UTF-8");
                // 5. Content: 邮件正文（可以使用html标签）
                message.setContent(emailBody, "text/html;charset=UTF-8");
                // 6. 设置发件时间
                message.setSentDate(new Date());
                // 7. 保存设置
                message.saveChanges();

                // 8. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
                transport.sendMessage(message, message.getAllRecipients());
                // 9. 关闭连接
                transport.close();
            }
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        } catch (UnsupportedEncodingException e) {
            System.out.println("检测到未知的编码");
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (TemplateException e) {
            throw new RuntimeException(e);
        }
        return message;
    }
//    /**
//     * 发送附件邮件
//     * @param sendMail    发件人邮箱
//     * @param receiveMail 收件人邮箱
//     * @param content 邮件内容
//     * @return
//     * @throws Exception
//     */
//    public MimeMessage sendAttachmentMail(String receiveMail, String content,String filePath,String fileName){
//        // 1. 创建一封邮件
//        MimeMessage message = new MimeMessage(sessionSend);
//        try {
//            // 2. From: 发件人
//            message.setFrom(new InternetAddress(myEmailAccount, "俞勐伟", "UTF-8"));
//            // 3. To: 收件人（可以增加多个收件人、抄送、密送）
//            message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "XX用户", "UTF-8"));
//            // 4. Subject: 邮件主题
//            message.setSubject("主题", "UTF-8");
//
//            MimeBodyPart bodyPart = new MimeBodyPart();
//            bodyPart.setContent(content, "text/html;charset=UTF-8");
//
//            MimeBodyPart bodyPart2 = new MimeBodyPart();
//            bodyPart2.attachFile(filePath);
//            bodyPart2.setFileName(fileName);
//
//            MimeMultipart mimeMultipart = new MimeMultipart();
//            mimeMultipart.addBodyPart(bodyPart);
//            mimeMultipart.addBodyPart(bodyPart2);
//
//            // 5. Content: 邮件正文（可以使用html标签）
//            message.setContent(mimeMultipart);
//            // 6. 设置发件时间
//            message.setSentDate(new Date());
//            // 7. 保存设置
//            message.saveChanges();
//            // 8. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
//            transport.sendMessage(message, message.getAllRecipients());
//            // 9. 关闭连接
//            transport.close();
//        } catch (MessagingException e) {
//            System.out.println("检测到邮件发送出现异常");
//        } catch (UnsupportedEncodingException e) {
//            System.out.println("检测到未知的编码");
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//        return message;
//    }
}